package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
/**
 *
 * @Title: apiChatWorkTime* @Description: Chat是否在工作时间，1 是，其他 否
 * @author: LiJuntao* @date 2020-05-09 下午1:02:36
 *
 */

public class apiChatWorkTime implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiChatWorkTime.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String dealSQL = "";

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        int remind;
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar today = Calendar.getInstance();
        log.debug("系统当前时间:" + df.format(today.getTime().getTime()));
        try {
            String workgroup_id = request.getParameter("workgroupId");
            log.debug("工作组ID:" + workgroup_id);

            dealSQL = "Select Date_Format(Freedate, '%Y-%m-%d') worktimeflag From c_Freedate_Chat c Where Current_Date = Date_Format(Freedate, '%Y-%m-%d') And (c.Workgroup_Id = ? Or c.Workgroup_Id = '') Limit 1";

            List<Map<String, Object>> sqlResult = jt.queryForList(dealSQL, workgroup_id);
            log.debug("节假日查询结果:" + sqlResult.toString());

            if (sqlResult.size() > 0) {
                log.debug("当前为非工作时间");
                remind = 0;
            } else {
                log.debug("当前不是非工作时间，返回-1检查工作组工作时间");
                remind = 1;
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            remind = -1;
        }

        return remind;
    }
}